using System;
using System.Collections.Generic;
using System.Text;
using ACS.Compiler.Tables.Modes;
using ACS.Compiler.Tree.Impl;
using ACS.Compiler.Util;

namespace ACS.Compiler.Tables
{
    public class DataTable
    {
        private static DataTable _instance;
        public static DataTable Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DataTable();
                }
                return _instance;
            }
        }

        private static DataTable _currentProcTable;
        public static DataTable CurrentProcTable
        {
            get
            {
                return _currentProcTable;
            }
        }

        public static void EnterProc(DataTable currentProcTable)
        {
            _currentProcTable = currentProcTable;
        }

        public static void ExitProc()
        {
            _currentProcTable = null;
        }

        private Dictionary<string, DataField> _table = new Dictionary<string, DataField>();

        public DataField AddData(TypeDeclarer declarer, string name, string ns)
        {
            string n = name;
            if (ns != null)
            {
                n = ns + "." + n;
            }
            if (_table.ContainsKey(n))
            {
                Logger.Instance.TraceError(string.Format("Field with name \"{0}\" is already declared", n));
            }
            DataField field = new DataField(ns, name, ModesTable.Instance.FindMode(declarer) );
            _table.Add(n, field);
            return field;
        }

        public DataField FindIdent(string curNamespace, string name)
        {
            DataField ret;
            string fieldName = name;
            if (curNamespace != null)
            {
                fieldName = curNamespace + "." + fieldName;
            }
            if (_table.TryGetValue(fieldName,out ret))
            {
                return ret;
            }
            return null;
        }
    }
}
